package com.kaikeba.controller;

import com.kaikeba.bean.Message;
import com.kaikeba.mvc.ResponseBody;
import com.kaikeba.service.AdminService;
import com.kaikeba.util.JSONUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @description:
 * @author: ManolinCoder
 * @time: 2021/8/29
 */
public class AdminController {
    @ResponseBody("/admin/login.do")//当注解只有一个值时键可以省略
    public String login(HttpServletRequest request, HttpServletResponse response){
        //1.接收参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2.调用service传参数并获取结果
        boolean result = AdminService.login(username, password);
        //3.根据结果,准备不同的数据
        Message msg = null;
        if (result){
            msg = new Message(0,"登录成功");
            //登录时间和ip的更新
            Date date = new Date();
            String ip = request.getRemoteAddr();//获取请求的ip地址
            AdminService.updateLoginTimeAndIP(username,date,ip);
            //登录成功保存用户信息
            request.getSession().setAttribute("adminUserName",username);
        }else {
            msg = new Message(-1,"登录失败");
        }
        //4.将数据转换为JSON
        String json = JSONUtil.toJSON(msg);
        //5.将JSON回复给ajax
        return json;
    }
}
